package com.samapp.indent;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.samapp.MyApplication;
import com.samapp.R;
import com.samapp.entity.Samples;
import com.samapp.photo.AlbumActivity;
import com.samapp.photo.GalleryActivity;
import com.samapp.utils.Common;
import com.samapp.utils.photo.Bimp;
import com.samapp.utils.photo.FileUtils;
import com.samapp.utils.photo.ImageItem;
import com.samapp.utils.photo.PublicWay;
import com.samapp.utils.photo.Res;

import com.dragon.httpclient_util.JsonUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

public class AddSampleDetailsActivity extends Activity implements OnClickListener {

	/** 返回按钮 */
	private Button btnBack = null;
	/** 完成 */
	private Button btnFinish = null;
	/** 样品序号 */
	private EditText etSn = null;
	/** 样品名称（中） */
	private EditText etCname = null;
	/** 样品名称(英) */
	private EditText etEname = null;
	/** 规格型号 */
	private EditText etModel;
	/** 样品数量 */
	private EditText etQty;
	/** 样品单位 */
	private EditText etUnit;
	/** 样品类别 */
	private EditText etType;
	/** 生产单位(中) */
	private EditText etProduceUnitcn;
	/** 生产单位(英) */
	private EditText etProduceUniten;
	/** 判定依据 */
	private EditText etBasis;
	/** 颜色物态 */
	private EditText etColor;
	/** 批号 */
	private EditText etBatchNumber;
	/** 样品性状 */
	private EditText etShape;
	/** 生产日期 */
	private EditText etProduceDate;
	/** 保质期 */
	private EditText etQualityDate;
	/** 商标 */
	private EditText etTrademark;
	/** 抽样基数 */
	private EditText etSampleBaseqty;
	/** 抽样环境 */
	private EditText etSampleEnv;
	/** 抽样地点 */
	private EditText etSamplePlace;
	/** 抽样方式 */
	private EditText etSampleMethod;
	/**样品图片*/
	private GridView noScrollgridview;
	/**样品图片适配器*/
	private GridAdapter adapter;
	/**样品图片缓存*/
	public static Bitmap bimap;
	
	private View parentView;
	private PopupWindow pop = null;
	private LinearLayout ll_popup;
	
	/** 样品图片上传结果 */
	private String upPictureMessage;
	/** 上传样品图片成功 */
	public static final int MSG_UP_PICTURE = 0x192;
	/** 上传样品图片失败 */
	public static final int MSG_UP_FAILURE = 0x193;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MSG_UP_PICTURE) {
				Toast.makeText(AddSampleDetailsActivity.this, upPictureMessage, Toast.LENGTH_SHORT).show();
			} else if (msg.what == MSG_UP_FAILURE) {
				Toast.makeText(AddSampleDetailsActivity.this, upPictureMessage, Toast.LENGTH_SHORT).show();
			}
		}
	};
	

	MyApplication myApplication = MyApplication.getApplicationInstance();

	/** 新添加的样品 */
	private Samples mySamples = new Samples();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Res.init(this);
		bimap = BitmapFactory.decodeResource(
				getResources(),
				R.drawable.icon_addpic_unfocused);
		PublicWay.activityList.add(this);
		parentView = getLayoutInflater().inflate(R.layout.activity_add_sample_details, null);
		setContentView(parentView);
		init();
	}

	private void init() {
		initView();
		initListener();
	}

	private void initView() {
		btnBack = (Button) findViewById(R.id.btn_back);
		btnFinish = (Button) findViewById(R.id.btn_finish);
		etSn = (EditText) findViewById(R.id.sn);
		etCname = (EditText) findViewById(R.id.cname);
		etEname = (EditText) findViewById(R.id.ename);
		etModel = (EditText) findViewById(R.id.model);
		etQty = (EditText) findViewById(R.id.qty);
		etUnit = (EditText) findViewById(R.id.unit);
		etType = (EditText) findViewById(R.id.type);
		etProduceUnitcn = (EditText) findViewById(R.id.produceUnitCn);
		etProduceUniten = (EditText) findViewById(R.id.produceUnitEn);
		etBasis = (EditText) findViewById(R.id.basis);
		etColor = (EditText) findViewById(R.id.sample_color);
		etBatchNumber = (EditText) findViewById(R.id.batchNumber);
		etShape = (EditText) findViewById(R.id.sample_shape);
		etProduceDate = (EditText) findViewById(R.id.produceDate);
		etQualityDate = (EditText) findViewById(R.id.qualityDate);
		etTrademark = (EditText) findViewById(R.id.trademark);
		etSampleBaseqty = (EditText) findViewById(R.id.sample_baseqty);
		etSampleEnv = (EditText) findViewById(R.id.sample_env);
		etSamplePlace = (EditText) findViewById(R.id.sample_place);
		etSampleMethod = (EditText) findViewById(R.id.sample_method);
		
		pop = new PopupWindow(AddSampleDetailsActivity.this);
		
		View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);
		ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		
		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);
		
		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		Button bt1 = (Button) view
				.findViewById(R.id.item_popupwindows_camera);
		Button bt2 = (Button) view
				.findViewById(R.id.item_popupwindows_Photo);
		Button bt3 = (Button) view
				.findViewById(R.id.item_popupwindows_cancel);
		parent.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				photo();
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(AddSampleDetailsActivity.this,
						AlbumActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_translate_in, R.anim.activity_translate_out);
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);	
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					ll_popup.startAnimation(AnimationUtils.loadAnimation(AddSampleDetailsActivity.this,R.anim.activity_translate_in));
					pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
				} else {
					Intent intent = new Intent(AddSampleDetailsActivity.this,
							GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});
	}

	private void initListener() {
		btnBack.setOnClickListener(this);
		btnFinish.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			closeActivity();
			finish();
			break;
		case R.id.btn_finish:
			setData();
			closeActivity();
			finish();
			break;
		}
	}

	private void setData() {
		//上传图片
		for(ImageItem item : Bimp.tempSelectBitmap){
			String url = myApplication.url + "uploadImg.htm";
			RequestParams params = new RequestParams();
			params.addBodyParameter("accessToken", "5C9.yx0S");
			params.addBodyParameter("type", Common.UP_SAMPLE);
			params.addBodyParameter("file", new File(item.getImagePath()));
			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

				@Override
				public void onSuccess(ResponseInfo<String> arg0) {
					Log.i("Long", arg0.result);
					upPictureMessage = JsonUtils.getValue(arg0.result, "msg");
					mySamples.getSamplePath().add(JsonUtils.getValue(arg0.result, "path"));
					mHandler.sendEmptyMessage(MSG_UP_PICTURE);
				}

				@Override
				public void onFailure(HttpException arg0, String arg1) {
					Log.i("Long", "上传样品图片失败：" + arg1.toString());
					upPictureMessage = "上传样品图片失败";
					mHandler.sendEmptyMessage(MSG_UP_FAILURE);
				}
			});
		}
		
		mySamples.setSn(etSn.getText().toString().trim());
		mySamples.setCname(etCname.getText().toString().trim());
		mySamples.setEname(etEname.getText().toString().trim());
		mySamples.setModel(etModel.getText().toString().trim());
		mySamples.setQty(etQty.getText().toString().trim());
		mySamples.setUnit(etUnit.getText().toString().trim());
		mySamples.setType(etType.getText().toString().trim());
		mySamples.setProduceUnitcn(etProduceUnitcn.getText().toString().trim());
		mySamples.setProduceUniten(etProduceUniten.getText().toString().trim());
		mySamples.setBasis(etBasis.getText().toString().trim());
		mySamples.setColor(etColor.getText().toString().trim());
		mySamples.setBatchNumber(etBatchNumber.getText().toString().trim());
		mySamples.setShape(etShape.getText().toString().trim());
		mySamples.setProduceDate(etProduceDate.getText().toString().trim());
		mySamples.setQualityDate(etQualityDate.getText().toString().trim());
		mySamples.setTrademark(etTrademark.getText().toString().trim());
		mySamples.setSampleBaseqty(etSampleBaseqty.getText().toString().trim());
		mySamples.setSampleEnv(etSampleEnv.getText().toString().trim());
		mySamples.setSamplePlace(etSamplePlace.getText().toString().trim());
		mySamples.setSampleMethod(etSampleMethod.getText().toString().trim());
		myApplication.newIndent.getSamples().add(mySamples);
	}
	
	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}
	
	private void closeActivity(){
		Bimp.tempSelectBitmap.clear();
		Bimp.max = 0;
		Intent intent = new Intent("data.broadcast.action");  
        sendBroadcast(intent);
		for(int i=0;i<PublicWay.activityList.size();i++){
			if (null != PublicWay.activityList.get(i)) {
				PublicWay.activityList.get(i).finish();
			}
		}
	}
	
	private static final int TAKE_PICTURE = 0x000001;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
				
				String fileName = String.valueOf(System.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				String imagePath = FileUtils.saveBitmap(bm, fileName);
				
				ImageItem takePhoto = new ImageItem();
				takePhoto.setImagePath(imagePath);
				takePhoto.setBitmap(bm);
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;
		}
	}
	
	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if(Bimp.tempSelectBitmap.size() == 9){
				return 9;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position ==Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}
}


